<?php
/**
 * Navcat(玩家管理)
 */
namespace Home\Controller;

use Think\Controller;

class WeixingController extends Controller
{

    public function index()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'weixing';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        //error_log(json_encode($tmpArr) . "\n\r", 3, 'error.log');
        if ($tmpStr == $signature && $echoStr) {
            echo $echoStr;
        } else {
            $this->reponseMsg();
        }
    }

    function reponseMsg()
    {
        //获取post过来的数据
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        /*   echo "<pre>";
           print_r($GLOBALS);*/
        //处理消息类型，并设置回复类型
        $postObj = simplexml_load_string($postArr);

        error_log($postObj->ToUserName . "\n\r". $postObj->FromUserName. "\n\r", 3, 'error.log');

        if (strtolower($postObj->MsgType) == 'event') {

            //回复用户消息
            $toUser = $postObj->FromUserName;
            $fromUser = $postObj->ToUserName;
            $time = time();
            $MsgType = 'text';
            $Content = "欢迎关注我们的公众账号";
            $template = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>";
            $info = sprintf($template, $toUser, $fromUser, $time, $MsgType, $Content);
            echo $info;
           // $this->insert_user($postObj->FromUserName);
            exit( $this->insert_user($postObj->FromUserName));
        }
        if (strtolower($postObj->MsgType) == 'text') {
            if ($postObj->Content == 'chenlong') {
                //回复用户消息
                $toUser = $postObj->FromUserName;
                $fromUser = $postObj->ToUserName;
                $time = time();
                $MsgType = 'text';
                $Content = "可以和我聊天";
                $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                             <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                             <Content><![CDATA[%s]]></Content>
                        </xml>";
                $info = sprintf($template, $toUser, $fromUser, $time, $MsgType, $Content);
                echo $info;
            }

        }
    }

    //用户信息写入数据库
    public function insert_user($id){
        $openid=$id;
        $user_info=$this->get_userinfo($openid);

        $data=array(
            'openid'=>$user_info['openid'],
            'headimgurl'=>$user_info['headimgurl'],
            'create_time'=>date("Y-m-d H:i:s",time()),
        );
        error_log( json_encode($data). "\n\r", 3, 'error.log');
        $row=M('wx_user')->where(array('openid'=>$user_info['openid']))->find();
        if(!$row && $data['headimgurl']!=null){
            M('wx_user')->add($data);
       }

    }

    //curl使用实例
    public function http_curl($url, $type = 'get', $res = 'json', $arr = '')
    {
        //1.初始化，创建一个新cURL资源
        $ch = curl_init();
        //2.设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//  不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//  不验证证书
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        //3.抓取URL并把它传递给浏览器
        //var_dump(curl_errno($ch));
        $output = curl_exec($ch);
        if ($res == 'json') {
            return json_decode($output, true);
        }
        //4.关闭cURL资源，并且释放系统资源
        curl_close($ch);
    }

    //获取token
    function getAccessToen()
    {

        session_start;

      /* if ($_SESSION['expire_time'] > time()) {

            return $_SESSION['access_token'];
        } else */{
            $appid = 'wx3c484176a1ad105d';
            $appsecret = 'b314e4774f61a3ac2d81a82e8d71d93f';
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret . '';

            $res = $this->http_curl($url, 'get', 'json');
            $access_token = $res['access_token'];
            $_SESSION['access_token'] = $access_token;
            $_SESSION['expire_time'] = time() + 3600;
            return $access_token;

       }
    }

    //获取token
    function getServerIp()
    {
        $token = 'tiv0O2CMS3RcDt2DX1dmbvKN22mybp_8BOUUle5ARD3zYNeu6y1IbznU4iuwir7f0UsXHAi0HwxIEk5Ov40DrCnm7R8tLqbWxEsw8m2qCl-HC0HG7hDVqKEYxdWIbb1LZGTeAJACJW';
        $url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=' . $token . '';
        $ch = curl_init();
        //2.设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //3.抓取URL并把它传递给浏览器
        $rel = curl_exec($ch);
        if (curl_errno($ch)) {
            var_dump(curl_errno($ch));
        }
        $token = json_decode($rel, true);
        //var_dump($token);
        //4.关闭cURL资源，并且释放系统资源
        curl_close($ch);
    }

    //微信自定义菜单
    public function defineditem()
    {
        $access_token = $this->getAccessToen();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $access_token;
        //echo $url;
        $post_arr = array(
            'button' => array(
                array(
                    'name' => urlencode('新手礼包'),
                    'type' => 'view',
                    'url' => 'http://dwc.gametu.com/think/index.php?g=Home&m=player&a=gift',

                ),
                array(
                    'name' => urlencode('安全中心'),
                    'type' => 'view',
                    'url' => 'http://dwc.gametu.com/think/index.php?g=Home&m=player&a=anquan',

                ),
                array(
                    'name' => urlencode('充值'),
                    'type' => 'view',
                    'url' => 'http://dwc.gametu.com/think/index.php?g=Home&m=player&a=pay',
                )

            )

        );
        $postjson = urldecode(json_encode($post_arr));
        $res = $this->http_curl($url, 'post', 'json', $postjson);
        var_dump($res);
    }

    //获取用户的 基本信息
    public function get_userinfo($openid)
    {
        $access_token = $this->getAccessToen();
        //$openid='oSxHQjmUaTOedK4EMZso3S-VfNhc';
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $res = $this->http_curl($url, 'get', 'json');
        return $res;
        //var_dump($res);
        //error_log(date("[Y-m-d H:i:s]") . " -[" . $_SERVER['REQUEST_URI'] . "] :" . $res . "\n", 3, "error.log");
    }

    //给用户发送模板消息
    public function send_msg()
    {
        $access_token = $this->getAccessToen();
        $openid = 'oSxHQjmUaTOedK4EMZso3S-VfNhc';
        $template_id = 'C5eSyO2Db607fmyPcMeGwL2lbszg3cO1cCtTNGn5Gnw';
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $array = array(
            'touser' => $openid,
            'template_id' => $template_id,
            'url' => 'www.baidu.com',
            "topcolor" => "#FF0000",
            'data' => array(
                'first' => array(
                    'value' => urlencode('恭喜你购买成功'),
                    'color' => '#ff0000',
                ),
                'accountType' => array(
                    'value' =>urlencode('账号') ,
                    'color' => '#ff0000',
                ),
                'account' => array(
                    'value' =>urlencode('baidu007') ,
                    'color' => '#ff0000',
                ),
                'productType' => array(
                    'value' =>urlencode('冲值获得') ,
                    'color' => '#173177',
                ),
                'number' => array(
                    'value' =>urlencode('100钻石') ,
                    'color' => '#173177',
                ),
                'amount' => array(
                    'value' =>urlencode('100元') ,
                    'color' => '#173177',
                ),
                'result' => array(
                    'value' =>urlencode('充值成功') ,
                    'color' => '#173177',
                ),
                'remark' => array(
                    'value' =>urlencode('祝你游戏愉快，谢谢!') ,
                    'color' => '#173177',
                ),
              /*  'date' => array(
                    'valve' => date('Y-m-d H:i:s', time()),
                    'color' => '#173177',
                ),*/
            ),
        );
        echo $postjson = urldecode(json_encode($array));
        $res = $this->http_curl($url, 'post', 'json', $postjson);
        var_dump($res);
    }


    //设置行业
    public function psot_industry()
    {
        $access_token = $this->getAccessToen();
        $url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=$access_token";
        $array = array(
            'industry_id1' => 5,
            'industry_id2' => 6,
        );
        echo $postjson = urldecode(json_encode($array));
        $res = $this->http_curl($url, 'post', 'json', $postjson);
        var_dump($res);
    }

    //获取设置的行业信息
    public function get_industry()
    {
        $access_token = $this->getAccessToen();
        $url = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=$access_token";
        $res = $this->http_curl($url, 'get', 'json');
        var_dump($res);
    }

    public function getBaseInfo(){
        $appid='wx3c484176a1ad105d';
        $redirect_uri=urlencode('http://dwc.gametu.com/think/index.php?g=Home&m=player&a=getUserOpenid');
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=123#wechat_redirect';
        header("location:".$url);
    }

    public function getUserOpenid(){
        $appid = 'wx3c484176a1ad105d';
        $appsecret = 'b314e4774f61a3ac2d81a82e8d71d93f';
        $code=$_GET['code'];
        $url=' https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        //var_dump($url);
        $res = $this->http_curl($url, 'get', 'json');
        var_dump($res);
    }
}